package Server;

import java.util.ArrayList;
import java.util.LinkedList;

public class DatabaseQueue implements Database, Runnable {
	private static Database _instance = null;
	private static final int _pollingInterval = 60*60000; // = 60 minutes/1hr

	private DataAccess db;
	private LinkedList<ArrayList<Integer>> queue;

	protected DatabaseQueue() {
		this.db = new DataAccess();
		this.queue = new LinkedList<ArrayList<Integer>>();
		new Thread(this).start();
	}

	@Override
	public boolean insert(ArrayList<Integer> data) {
		synchronized (queue) {
			queue.add(data);
		}
		return true;
	}

	@Override
	public ArrayList<Integer> get() {
		return new ArrayList<Integer>(); // get not possible when not holding the database
	}

	public static Database getInstance() {
		synchronized (DatabaseQueue.class) {
			if (_instance == null) {
				_instance = new DatabaseQueue();				
			}
			return _instance;
		}
	}

	@Override
	public void run() {
		while (true) {
			if (db.open()) {
				while (!queue.isEmpty()) {
					synchronized (queue) {
						db.insert(queue.removeFirst());
					}
				}				
				db.release();
			}
			try {
				Thread.sleep(_pollingInterval);
			} catch (Exception e) {

			}
		}

	}


}
